﻿using System;
using UnityEngine;

/// <summary>
/// 
/// </summary>
public static class GameObjectExtension
{
    /// <summary>
    /// 创建|模型实例
    /// </summary>
    /// <param name="primitiveType"></param>
    /// <returns>
    /// 返回 模型对象 <see cref="GameObject"/>
    /// </returns>
    public static GameObject DoCreatePrimitiveInstance(PrimitiveType primitiveType)
    {
        GameObject primitive = GameObject.CreatePrimitive(primitiveType);
        primitive.name = $"实例 {primitiveType} | {Guid.NewGuid()}";

        return primitive;
    }

    /// <summary>
    /// 获取|模型实例
    /// </summary>
    public static void DoGetFromPool(this GameObject target)
    {
        target.SetActive(true);
    }


    /// <summary>
    /// 重置GameObject的变换和物理状态
    /// </summary>
    public static void DoResetToPool(this GameObject gameObject, Transform parent = null)
    {
        gameObject.SetActive(false);
        gameObject.transform.SetParent(parent);
        gameObject.transform.SetPositionAndRotation(Vector3.zero, Quaternion.identity);
        gameObject.transform.localScale = Vector3.one;

        // 重置物理状态
        if (gameObject.TryGetComponent<Rigidbody>(out var rigidbody))
        {
            rigidbody.velocity = Vector3.zero;
            rigidbody.angularVelocity = Vector3.zero;
        }
    }

    /// <summary>
    /// 配置GameObject的变换和材质
    /// </summary>
    public static void ConfigureForUse(this GameObject gameObject, Vector3 position, Vector3 scale, Material material = null, Transform parent = null)
    {
        gameObject.SetActive(true);
        gameObject.transform.position = position;
        gameObject.transform.localScale = scale;
        gameObject.transform.SetParent(parent);

        if (material != null && gameObject.TryGetComponent<Renderer>(out var renderer))
        {
            renderer.material = material;
        }
    }

    /// <summary>
    /// 判断 GameObject 是否为指定 PrimitiveType
    /// </summary>
    public static bool IsPrimitiveType(this GameObject gameObject, PrimitiveType primitiveType)
    {
        var objType = gameObject.GetPrimitiveType();
        return objType.HasValue && objType.Value == primitiveType;
    }

    /// <summary>
    /// 获取 GameObject 的 PrimitiveType
    /// </summary>
    public static PrimitiveType? GetPrimitiveType(this GameObject gameObject)
    {
        foreach (PrimitiveType primitiveType in Enum.GetValues(typeof(PrimitiveType)))
        {
            if (gameObject.name.Contains(primitiveType.ToString()))
            {
                return primitiveType;
            }
        }
        return null;
    }
}